package com.titleevaluation.service;

import com.titleevaluation.entity.Application;
import com.titleevaluation.entity.Punishments;
import com.titleevaluation.repository.ApplicationRepository;
import com.titleevaluation.repository.PunishmentsRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class PunishmentsService {

    private final PunishmentsRepository punishmentsRepository;
    private final ApplicationRepository applicationRepository;

    public PunishmentsService(PunishmentsRepository punishmentsRepository, ApplicationRepository applicationRepository) {
        this.punishmentsRepository = punishmentsRepository;
        this.applicationRepository = applicationRepository;
    }

    public Punishments createPunishments(Long applicationId, Punishments punishments) {
        Application application = applicationRepository.findById(applicationId)
                .orElseThrow(() -> new RuntimeException("Application not found"));
        punishments.setApplication(application);
        punishments.setCreatedAt(LocalDateTime.now());
        punishments.setUpdatedAt(LocalDateTime.now());
        return punishmentsRepository.save(punishments);
    }

    public List<Punishments> getPunishmentsByApplicationId(Long applicationId) {
        return punishmentsRepository.findByApplicationId(applicationId);
    }

    public Optional<Punishments> getPunishmentsById(Long id) {
        return punishmentsRepository.findById(id);
    }

    public Punishments updatePunishments(Long id, Punishments updatedPunishments) {
        Punishments existingPunishments = punishmentsRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Punishments not found"));

        existingPunishments.setPunishmentType(updatedPunishments.getPunishmentType());
        existingPunishments.setPunishmentName(updatedPunishments.getPunishmentName());
        existingPunishments.setPunishmentDate(updatedPunishments.getPunishmentDate());
        existingPunishments.setPunishingDepartment(updatedPunishments.getPunishingDepartment());
        existingPunishments.setPunishmentNo(updatedPunishments.getPunishmentNo());
        existingPunishments.setRemarks(updatedPunishments.getRemarks());
        existingPunishments.setUpdatedAt(LocalDateTime.now());

        return punishmentsRepository.save(existingPunishments);
    }

    public void deletePunishments(Long id) {
        punishmentsRepository.deleteById(id);
    }
}

